package com.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.model.Group;
import com.service.BranchService;
import com.service.GroupService;

@Controller
public class GroupController {

	@Autowired
	private GroupService groupService;
	@Autowired
	private BranchService branchService;


	// REquest to add group.. Give blank form of group
	@RequestMapping(value="/user/addGroup",method=RequestMethod.GET)
	public String addGroup(ModelMap model,HttpSession session,@ModelAttribute("command") Group group) {
		String branch=(String) session.getAttribute("branch");
		model.put("groupList",groupService.getAllForUser(branch));
		return "group";
	}

	// add group details into database
	@RequestMapping(value = "/user/saveGroup", method = RequestMethod.POST)
	public String saveGroup(@ModelAttribute("command") Group group,HttpSession session) {
		groupService.add(session.getAttribute("branch").toString(),group);
		return "redirect:/user/addGroup.htm";
	}

	// give group details from database
	@RequestMapping("/user/editGroup")
	public ModelAndView editGroup(@ModelAttribute("command") Group group,
			HttpServletRequest request)
	{
		Integer id=Integer.parseInt(request.getParameter("id"));
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("group",groupService.get(id));
		return new ModelAndView("group",model);
	}

	//delete Group
	@RequestMapping("/user/deleteGroup")
	public String deleteGroup(HttpServletRequest request)
	{
		Integer id=Integer.parseInt(request.getParameter("id"));
		groupService.delete(id);
		return "redirect:/user/addGroup.htm";
	}


}
